package org.yh.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.yh.mapper.PermissionMapper;
import org.yh.mapper.UserMapper;
import org.yh.model.Permission;
import org.yh.model.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yh
 * @Description:
 * @Date: Created in 16:25 2018/12/10
 * @Modified By:
 */
@Service
@Slf4j
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户名：" + username);
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        List<User> users = userMapper.selectByMap(map);
        //判断用户名是否存在
        if (users.size() != 0) {
            User user = users.get(0);
            List<Permission> pers = permissionMapper.findPermissionsByUserId(user.getId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            for (Permission per : pers) {
                if (per != null && per.getName() != null) {
                    log.info("权限：" + per.getName());
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(per.getName());
                    //此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            //String ps = PasswordEncoderUtil.passwordEncoder(user.getPassword());
            //log.info("加密后：" + ps);
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
        } else {
            log.info("用户：" + username + "不存在");
            throw new MyUsernameNotFoundException("用户：" + username + "不存在");
        }
    }

}
